package test._interface;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.opencsv.CSVReader;
import com.taobao.api.ApiException;
import dingding.DingTalk;
import dingding.dao.PLC;
import dingding.dao.configInformation;
import dingding.dingdingAlarm;
import org.mozilla.universalchardet.UniversalDetector;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;

import test._interface.service.ItestService;
import test._interface.service.impl.testServiceImpl;

public class test {
    public static void main(String[] args) throws ApiException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
//            System.setOut(new PrintStream(System.out, true, "UTF-8"));
//        String currentDirectory = System.getProperty("user.dir");
//        String filePath =currentDirectory+ File.separator+ "dingdingSendConfig.ini";
        String filePath = Paths.get("").toAbsolutePath().resolve("dingdingSendConfig.ini").toString();
//        System.out.println(filePath);
        configInformation config = new configInformation();
        Map<String, String> keyValueMap = INIReader.readINIFile(filePath,config);
//            String file = "C:\\Users\\Administrator\\Desktop\\钉钉报警\\Alarm_log1.csv";//file path faultlist
//        System.out.println(keyValueMap);
        if(keyValueMap != null ) {
            config.setFile(keyValueMap.get("filepath"));
//            String plcNAME = "CPU_BA12/CPU_PBS3";
            String plcNAME = keyValueMap.get("plcName");
            config.setPlcNAME(plcNAME);
            config.setPlcLIST(plcNAME.split("/"));
            String classNAME = keyValueMap.get("MsgClass");
            config.setClassNAME(classNAME);
//                String[] classlist = classNAME.split("/");
            config.setClasslist(classNAME.split("/"));
            String faultNAME = keyValueMap.get("faults");
            config.setFaultNAME(faultNAME);
            config.setFaultlist(faultNAME.split("/"));
//                String[] faultlist = faultNAME.split("/");
            config.setWebhook(keyValueMap.get("webhook"));
            config.setSecret(keyValueMap.get("secret"));
//                String webhook = keyValueMap.get("webhook");
        }else{
//                config.setClasslist(new String[] );
        }
//            System.out.println("secret:  "+config.getSecret());
//            MyUtils.DingTalkExample(config,"大家好");
        ItestService testSS = new testServiceImpl();
        testSS.DingTalkExample(config, "舒服点舒服舒服");
    }

}
// 读取ini配置文件
class INIReader {
    public static Map<String, String> readINIFile(String filePath, configInformation config) {
        Map<String, String> keyValueMap = new HashMap<>();
        String encoding = MyUtils.codeType(filePath);
        encoding = (encoding==null?"UTF-8":encoding);
        try (BufferedReader reader = new BufferedReader(
                new FileReader(filePath, Charset.forName(encoding))
        )) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();

                // Skip empty lines and comments
                if (line.isEmpty() || line.startsWith(";")) {
                    continue;
                }
//                new String(columns[i].getBytes("ISO-8859-1"), "UTF-8");
                // Split line into key-value pair
                int equalsIndex = line.indexOf("=");
                if (equalsIndex != -1) {
                    String key = line.substring(0, equalsIndex).trim();
                    String value = line.substring(equalsIndex + 1).trim();
//                    value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
                    keyValueMap.put(key, value);
                }

            }
            config.setRepon(null);
        } catch (IOException e) {
//            e.printStackTrace();
            config.setRepon("读取配置文件失败！请确保配置文件在同目录下后重启软件，或者直接窗口输入信息后运行！\n");
//            System.out.println("66666读取配置文件失败！");
            return null;
        }

        return keyValueMap;
    }
}

// 工具类
class MyUtils {
    private void MyUtils() {
    }

    ;

    //    判断元素是否在列表中
    public static <E> boolean charinlist(E[] LIST, E e) {
        boolean contains = false;
        for (E element : LIST) {
            if (element.equals(e)) {
                contains = true;
                break;
            }
        }
        return contains;
    }

    ;

    //    判断日期是否跟当天一致
    public static boolean isdate(String dateString) {
        boolean bool = false;
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String formattedDateTime = dtf.format(currentDateTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        try {
//            Date date = sdf.parse(dateString.strip());
            Date date = sdf.parse(dateString.trim());  // 替换 strip() 为 trim()
            Date date2 = sdf.parse(formattedDateTime);
            if (date.equals(date2)) {
                bool = true;
//                System.out.println(date2);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return bool;
    }

    ;

    //    获取当前日期时间
    public static String getDate() {
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        String formattedDateTime = dtf.format(currentDateTime);
        return formattedDateTime;
    }

    ;


    // 打印数组
    public static void soutArrary(List ARR) {
        String ms = "[";
        for (int i = 0; i < ARR.size(); i++) {
            if (i != 0) {
                ms = ms + ",";
            }
            ms = ms + ARR.get(i);
        }
        ms = ms + "]";
        System.out.println(ms);
    }

    public static void soutArrary(String[] ARR) {
        String ms = "[";
        for (int i = 0; i < ARR.length; i++) {
            if (i != 0) {
                ms = ms + ",";
            }
            ms = ms + ARR[i];
        }
        ms = ms + "]";
        System.out.println(ms);
    }

    // 获取文件编码格式
    public static String codeType(String filename) {
        String code = null;
        try {
            byte[] bytes = Files.readAllBytes(Paths.get(filename));
            UniversalDetector detector = new UniversalDetector(null);
            detector.handleData(bytes, 0, bytes.length);
            detector.dataEnd();
            String encoding = detector.getDetectedCharset();
            if (encoding != null) {
//                    System.out.println("Detected encoding: " + encoding);
                code = encoding;
            } else {
//                    System.out.println("Unable to detect encoding.");
            }
            detector.reset();
        } catch (IOException e) {
//                e.printStackTrace();
        }
        return code;

    }
    //    获取钉钉Token
    public static String getToken(String url,String AppKey,String AppSecret) throws RuntimeException {
        try {
            DefaultDingTalkClient client = new DefaultDingTalkClient(url);
            OapiGettokenRequest request = new OapiGettokenRequest();

            request.setAppkey(AppKey);
            request.setAppsecret(AppSecret);
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            String accessToken = response.getAccessToken();
            return accessToken;
        } catch (ApiException e) {
            throw new RuntimeException();
        }

    }

}


